<script setup lang="ts">
// 应用的主界面，目前只显示标题
import { computed, onMounted, onUnmounted, ref } from "vue";
import { Search, User } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { messageDB } from "@/utils/database";
import type { Message } from "@/utils/database";
import SessionList from "@/components/SessionList.vue";
import MessageList from "@/components/MessageList.vue";
import SettingList from "@/components/SettingList.vue";
// 移除WebSocketManager的直接导入，使用主进程管理的WebSocket
import { BASE_URL_WS } from "@/utils/baseURL";
import { handleMessage } from "@/utils/handleMessage";
import { dataFormat } from "@/utils/dataFormatting";

// 消息框
const messageBox = ref<any>(null);
// 聊天状态
const chatStatus = ref(true);
// 当前选中的用户索引
const currentSelectIndex = ref(-1);
// 当前选中的用户
const currentSelectUser = ref<{ id: string; nickname: string } | null>(null);
// 用户自己数据
const userSelf = ref<{ id: string; nickname: string } | null>(null);
// 输入的消息
const textarea = ref("");
// 搜索框输入
const input = ref("");
// 聊天记录
const messages = ref<Message[]>([]);
// 好友申请列表
const friendRequestList = ref<any[]>([]);
// 本地消息Id
const localMsgId = (): string =>
  `local_${Date.now()}_${Math.random().toString(36).substring(2)}`;

// 选择用户
const selectUser = (item: number) => {
  if (currentSelectIndex.value === item) {
    currentSelectIndex.value = -1;
    chatStatus.value = true;
  } else {
    currentSelectIndex.value = item;
    chatStatus.value = false;
    currentSelectUser.value = {
      id: item.toString(),
      nickname: `用户${item}`,
    };
    messages.value = [];
    loadMsg(); // 加载当前会话的消息

    input.value = "";
  }
};

// 根据当前联系人生成会话Id
const currentConversationId = computed((): string => {
  if (!currentSelectUser.value) return "";
  // 会话ID规则：当前用户ID_对方用户ID
  return `${userSelf.value?.id || ""}_${currentSelectUser.value.id}`;
});

// 获取消息列表
const loadMsg = async (): Promise<void> => {
  try {
    const conversationId = currentConversationId.value;
    console.log("正在加载会话消息:", conversationId);
    // 确保加载消息时不阻塞UI
    const loadedMessages: Message[] =
      (await messageDB?.getMessagesByConversation(conversationId)) || [];
    console.log("消息加载成功，共", loadedMessages?.length || 0, "条消息");
    // 使用Vue的响应式更新机制确保DOM更新
    messages.value = [...loadedMessages];
  } catch (error) {
    console.error("加载消息失败:", error);
    messages.value = [];
  }
};

// 打开好友申请窗口
const openFriendRequest = () => {
  try {
    (window as any).electronAPI.openFriendRequestWindow();
  } catch (err) {
    console.log("打开好友申请窗口失败", err);
  }
};

// 发送消息
const sendMsg = async () => {
  if (textarea.value.trim() === "") {
    return;
  }
  if (!userSelf.value) {
    ElMessage.error("用户错误");
    return;
  }
  try {
    console.log("发送消息");
    const localId = localMsgId();
    const newMessage: Omit<Message, "id" | "timestamp"> = {
      local_id: localId,
      content: textarea.value,
      conversation_id: currentConversationId.value,
      status: 0,
      sender_id: userSelf.value?.id,
    };
    // 保存到本地数据库
    await messageDB?.addMessage(newMessage);
    await loadMsg(); // 刷新消息列表
    textarea.value = "";
    console.log("发送消息成功");

    // 通过主进程发送消息到服务器
    if (window.electronAPI && window.electronAPI.wsSend) {
      const messageData = {
        type: "message",
        content: newMessage.content,
        sender_id: newMessage.sender_id,
        receiver_id: currentSelectUser.value?.id,
        conversation_id: newMessage.conversation_id,
        local_id: newMessage.local_id,
        timestamp: new Date().toISOString(),
      };
      const success = await window.electronAPI.wsSend(messageData);
      console.log("消息发送到服务器结果:", success);
    }
  } catch (error) {
    console.error("发送消息失败:", error);
  }
};

// 处理搜索框输入
const handleCompositionEnd = () => {
  if (input.value === "") {
    return;
  }
  ElMessage.success(`搜索了${input.value}`);
};

/**
 * 计算两个消息时间的间隔是否大于5分钟
 * @param currentMsg 当前消息
 * @param previousMsg 上一条消息
 * @returns 是否显示时间
 */
const shouldShowTime = (
  currentMsg: Message,
  previousMsg: Message | null
): boolean => {
  if (!previousMsg) {
    // 如果是第一条消息，总是显示时间
    return true;
  }
  const date1 = new Date(currentMsg.timestamp || "");
  const date2 = new Date(previousMsg.timestamp || "");
  return Math.abs(date2.getTime() - date1.getTime()) > 5 * 60 * 1000;
};

// 判断是否是自己消息
const isOwnMsg = (msg: Message): boolean => {
  return msg.sender_id === currentSelectUser.value?.id;
};

// 处理回车发送消息
const handleEnter = (event: KeyboardEvent) => {
  if (!event.shiftKey) {
    // 纯回车键：发送消息
    event.preventDefault();
    sendMsg();
  }
  // Shift+Enter：不处理，允许换行
};

// 处理接收到的WebSocket消息
const handleWebSocketMessage = async (message: any) => {
  console.log("main -> 收到WebSocket消息:", dataFormat(message));
  handleMessage(message, {
    onFriendRequestUpdate: async () => {
      await getFriendList();
    },
  });
};

// 初始化WebSocket连接
const initWebSocket = (userId: string) => {
  try {
    // 通过主进程初始化WebSocket连接
    if (
      window.electronAPI &&
      window.electronAPI.wsInit &&
      window.electronAPI.onWsMessage
    ) {
      const wsUrl = BASE_URL_WS.dev;

      // 初始化连接
      window.electronAPI
        .wsInit(userId, wsUrl)
        .then(() => {
          console.log("WebSocket连接初始化成功");
          // 注册全局WebSocket消息监听器
          window.electronAPI.onWsMessage(handleWebSocketMessage);
          // 注册全局websocket状态变化监听
          window.electronAPI.onWsStatusChange(async (status) => {
            if (
              (status === "连接错误" || status === "已断开") &&
              !messageBox.value
            ) {
              messageBox.value = ElMessage.error({
                message: "断线重连中...",
                duration: 0,
              });
            }
            if (status === "已连接") {
              if (messageBox.value) {
                messageBox.value.close();
                ElMessage.success({
                  message: "重连成功",
                  duration: 1000,
                });
              }
              await getFriendList();
            }
          });
        })
        .catch((error) => {
          console.error("主进程WebSocket初始化失败:", error);
        });
    }
  } catch (error) {
    console.error("WebSocket连接初始化失败:", error);
  }
};

// 获取用户好友列表
const getFriendList = async () => {
  try {
    // 重新获取最新的好友申请列表
    if (userSelf.value?.id) {
      const friendRequests = await messageDB?.getFriendRequestsByToUserId(
        userSelf.value.id,
        "pending"
      );
      friendRequestList.value = friendRequests || [];
      console.log("好友申请列表:", friendRequestList.value);
    }
  } catch (err) {
    console.error("获取好友列表失败:", err);
  }
};

// 断开WebSocket连接
const disconnectWebSocket = () => {
  try {
    if (window.electronAPI && window.electronAPI.wsDisconnect) {
      window.electronAPI.wsDisconnect();
      console.log("WebSocket连接已断开");
    }
  } catch (error) {
    console.error("断开WebSocket连接失败:", error);
  }
};

// 生命周期钩子 组件挂载完成
onMounted(async () => {
  if ((window as any).electronAPI) {
    const user = await (window as any).electronAPI.store.get("user");
    // 挂载完成后 初始化用户数据
    userSelf.value = user;
    // 初始化WebSocket连接
    initWebSocket(user.id);
  } else {
    console.log("未在Electron环境中运行");
  }
  // 监听好友申请列表更新
  window.electronAPI.onFriendRequestUpdate(async () => {
    console.log("收到好友申请列表更新");
    await getFriendList();
  });
});

// 生命周期钩子 组件卸载前
onUnmounted(() => {
  // 断开WebSocket连接
  disconnectWebSocket();
});
</script>

<template>
  <div class="container">
    <el-row>
      <el-col class="left-col">
        <div class="grid-content">
          <div class="tool">
            <el-input
              v-model="input"
              class="input"
              placeholder="搜索"
              clearable
              :prefix-icon="Search"
              @input="handleCompositionEnd"
            />
            <el-badge
              :value="friendRequestList?.length || 0"
              :show-zero="false"
              class="badge"
              @click="openFriendRequest"
            >
              <el-icon size="20" color="#909399" style="cursor: pointer">
                <User />
              </el-icon>
            </el-badge>
            <SettingList />
          </div>
          <SessionList
            @select-user="selectUser"
            :current-select-index="currentSelectIndex"
          ></SessionList>
        </div>
      </el-col>
      <div class="divider"></div>
      <el-col class="right-col">
        <div class="grid-content chat" v-if="!chatStatus">
          <div class="title">
            <span>{{ currentSelectUser?.nickname }}</span>
          </div>
          <el-divider />
          <div class="content">
            <div class="content-inner">
              <MessageList
                :messages="messages"
                :is-own-msg="isOwnMsg"
                :should-show-time="shouldShowTime"
              ></MessageList>
            </div>
          </div>
          <el-divider />
          <div class="send-msg">
            <div class="input-area">
              <el-input
                v-model="textarea"
                :rows="2"
                type="textarea"
                placeholder="请输入要发送的内容"
                class="custom-textarea"
                @keyup.enter="handleEnter"
              />
            </div>
            <div class="send">
              <el-button
                type="success"
                class="send-btn"
                :disabled="textarea === ''"
                @click="sendMsg"
                >发送</el-button
              >
            </div>
          </div>
        </div>
        <div class="grid-content welcome" v-else>
          <div class="tip">点击用户开始发送消息</div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="less" scoped>
.container {
  height: 100vh;
  .el-row {
    display: flex;
    flex-wrap: nowrap; /* 防止换行 */ // 因为这个导致聊天消息测试时当数据过长则直接把聊天框整体挤到页面下面去了
    height: 100%;
    .left-col {
      width: 260px !important; /* 固定宽度为200像素 */
      height: 100%;
      flex: 0 0 auto !important; /* 禁止伸缩，保持固定尺寸 */
      background-color: #fff;
      overflow-y: scroll;
      flex-shrink: 0; /* 禁止收缩 */
      /* 调整滚动条样式 - WebKit浏览器（Chrome, Safari等） */
      &::-webkit-scrollbar {
        width: 6px; /* 滚动条宽度 */
      }
      &::-webkit-scrollbar-track {
        background: #f1f1f1; /* 滚动条轨道背景色 */
        border-radius: 3px; /* 轨道圆角 */
      }
      &::-webkit-scrollbar-thumb {
        background: transparent;
        border-radius: 3px; /* 滑块圆角 */
        transition: background 0.3s ease; /* 过渡效果 */
      }
      /* 鼠标移入时显示 */
      &:hover {
        &::-webkit-scrollbar-thumb {
          background: #c1c1c1;
        }

        &::-webkit-scrollbar-thumb:hover {
          background: #a8a8a8;
        }
      }
      /* 调整滚动条样式 - Firefox */
      scrollbar-width: thin; /* 滚动条宽度：thin, auto, none */
      /* Firefox */
      scrollbar-color: transparent transparent;
      &:hover {
        scrollbar-color: #c1c1c1 #fafafa; /* 滑块颜色 轨道颜色 */
      }
      .tool {
        display: flex;
        align-items: center;
        padding: 6px;
        border-bottom: 1px solid #eaeaea;
        &:deep(.el-input__wrapper.is-focus) {
          box-shadow: 0 0 0 1px #dcdfe6 inset !important; /* 使用默认边框颜色 */
        }
        .badge {
          margin: 0 18px 0 6px;
          line-height: 10px;
          &:deep(.el-badge__content) {
            margin-right: 2px;
            font-size: 10px;
          }
        }
      }
    }
    .right-col {
      flex: 1 1 auto !important; /* 可伸缩，占据剩余空间 */
      height: 100%;
      min-width: 0; /* 允许内容换行，防止溢出 */
      background-color: #f8f8f8;
      .chat {
        height: 100%;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        .title {
          padding: 0 20px;
          height: 50px; /* 固定高度 */
          display: flex;
          align-items: center;
          justify-content: space-between;
          flex-shrink: 0; /* 防止收缩 */
          span {
            font-weight: bold;
          }
        }
        /* 如果需要保持正常的阅读顺序，可以这样包装内容 */
        .content-inner {
          display: flex;
          flex-direction: column;
          padding: 10px 0;
          min-height: min-content;
        }
        .content {
          flex: 1; /* 占据剩余所有空间 */
          padding: 0 20px;
          overflow-y: auto; /* 关键：启用垂直滚动 */
          display: flex;
          flex-direction: column-reverse; /* 关键：反向排列，让内容从底部开始 */
          /* 调整滚动条样式 - WebKit浏览器（Chrome, Safari等） */
          &::-webkit-scrollbar {
            width: 6px; /* 滚动条宽度 */
          }
          &::-webkit-scrollbar-track {
            background: #f1f1f1; /* 滚动条轨道背景色 */
            border-radius: 3px; /* 轨道圆角 */
          }
          &::-webkit-scrollbar-thumb {
            background: transparent;
            border-radius: 3px; /* 滑块圆角 */
            transition: background 0.3s ease; /* 过渡效果 */
          }
          /* 鼠标移入时显示 */
          &:hover {
            &::-webkit-scrollbar-thumb {
              background: #c1c1c1;
            }

            &::-webkit-scrollbar-thumb:hover {
              background: #a8a8a8;
            }
          }
          /* 调整滚动条样式 - Firefox */
          scrollbar-width: thin; /* 滚动条宽度：thin, auto, none */
          /* Firefox */
          scrollbar-color: transparent transparent;
          &:hover {
            scrollbar-color: #c1c1c1 #fafafa; /* 滑块颜色 轨道颜色 */
          }
        }
        .send-msg {
          padding: 10px;
          height: 180px; /* 固定高度 */
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          justify-content: flex-start;
          flex-shrink: 0; /* 防止收缩 */
          .input-area {
            width: 100%;
            height: 74%;
            /* 使用深度选择器, 自定义文本域的背景颜色 */
            .custom-textarea {
              height: 100%;
              &:deep(.el-textarea__inner) {
                height: 100% !important;
                background-color: #f8f8f8; /* 浅蓝色背景 */
                // 无阴影
                box-shadow: none;
                // 移除文本域右下角的显示
                resize: none;
              }
            }
          }
          .send {
            width: 100px;
            .send-btn {
              margin-top: 10px;
              width: 100%;
            }
          }
        }
      }
      .welcome {
        display: flex;
        align-items: center;
        justify-content: center;
        .tip {
          font-size: 30px;
          font-weight: bold;
          color: rgba(137, 141, 145, 0.3);
          transform: skew(-10deg) rotateX(45deg);
          text-shadow: 1px 1px 0 rgba(137, 141, 145, 0.3),
            2px 2px 0 rgba(137, 141, 145, 0.3),
            3px 3px 0 rgba(137, 141, 145, 0.3),
            4px 4px 0 rgba(137, 141, 145, 0.3), 6px 6px 10px rgba(0, 0, 0, 0.2);
          transition: all 0.3s ease;
        }
      }
    }
    .divider {
      width: 1px;
      background-color: #d8dce4;
    }
    .grid-content {
      height: 100%;
    }
  }
}
// 修改divider组件的默认样式
.el-divider--horizontal {
  margin: 0;
}
</style>